<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
ul{margin:0;padding:0;}
li{list-style-type:none;}
#navlist li{float:left;padding:0 15px;line-height:40px;font-size:20px;}
#navlist li.curr{color:#FFF;background:#F00;}
.box{padding-top:40px;}
.box h1{font-size:26px;text-align:center;margin:0;}
div.book{height:400px;}
div.phone{height:700px;}
div.jiadian{height:800px;}
div.shuma{height:450px;}
/*
li book
div book
*/
</style>
</head>
<body>
<div style="width:100%;height:300px;background:#2888EE;"></div>
<div id="nav" style="width:100%;height:40px;background:#DDD;">
	<ul id="navlist" style="width:600px;margin:0 auto;">
		
	</ul>
</div>

<div class="box book">
	<h1>图书列表</h1>
</div>
<div class="box jiadian">
	<h1>家电列表</h1>
</div>
<div class="box phone">
	<h1>手机列表</h1>
</div>

<div class="box shuma">
	<h1>数码列表</h1>
</div>

<div style="height:800px;background:#089B26"></div>
<script>
function $(s){
	return document.querySelectorAll(s);
}
var nav=$("#nav")[0],navlist=$("#navlist")[0],oli,odiv=$(".box")
arr=[
	{txt:"图书",cname:"book"},
	{txt:"手机",cname:"phone"},
	{txt:"家电",cname:"jiadian"},
	{txt:"数码",cname:"shuma"}
];
function init(arr){
	for(var i=0;i<arr.length;i++){
		var li=document.createElement("li");
		li.innerHTML=arr[i].txt;
		li.className=arr[i].cname;
		navlist.appendChild(li);
	}
	oli=$("#navlist li");
}
init(arr);
//保证oli组合里的li都能被获取，包含动态添加的li
function addClass(dom,cla){
	var cname=dom.className;
	if(cname){
		if(cname.indexOf(cla)==-1){
			dom.className+=" "+cla;
		}
	}else{
		dom.className=cla;
	}
}
function removeClass(dom,cla){
	var cname=dom.className;
	if(cname){
		if(cname.indexOf(cla)!=-1){
			dom.className=cname.replace(" "+cla,"")
		}
	}
}

navlist.addEventListener("click",function(e){
	if(e.target.tagName=="LI"){
		//点击的li对应的div
		var c=e.target.className;//book
		for(var i=0;i<oli.length;i++){
			//oli[i].className=""
			removeClass(oli[i],"curr");
		}
		addClass(e.target,"curr");






		for(var i=0;i<odiv.length;i++){
			if(odiv[i].className.indexOf(c)!=-1){
				var dtop=document.documentElement.scrollTop,
				ntop=odiv[i].offsetTop;
				if(dtop>ntop){
					toUp(dtop,ntop);
				}else{
					toDown(dtop,ntop);
				}
				
			}
		}
	}
})
function toDown(dtop,ntop){
	if(Math.round(dtop)>=ntop){
		return;
	}else{
		window.scrollTo(0,dtop);
		setTimeout(function(){
			toDown(dtop+(ntop-dtop)/10,ntop);
		},7)
	}
}
function toUp(dtop,ntop){
	if(Math.round(dtop)<=ntop){
		return;
	}else{
		window.scrollTo(0,dtop);
		setTimeout(function(){
			toUp(dtop-(dtop-ntop)/10,ntop);
		},7)
	}
}
window.onscroll=function(){//滚动事件
	if(document.documentElement.scrollTop>=300){
		nav.style.position="fixed";
		nav.style.left="0";
		nav.style.top="0";
	}else{
		nav.style.position="static";
	}
}
</script>	
</body>
</html>